﻿using System.Linq;
using Wombat.Data.Model;

namespace Web.Models.Helpers
{
    public static class DefaultsHelper
    {
        public static Cluster GetDefaultCluster(WombatEntities db)
        {
                var clust = db.Clusters.FirstOrDefault(c => c.Name == "UNKNOWN");
                if (clust == null)
                {
                    var newClust = new Cluster()
                        {
                            Comments = "Unknown cluster",
                            Domain = GetDefaultDomain(db),
                            Database = "UNKNOWN"
                        };
                    db.AddToClusters(newClust);
                    db.SaveChanges();
                    return newClust;
                }
                return clust;
        }

        public static Domain GetDefaultDomain(WombatEntities db)
        {
            var domain = db.Domains.FirstOrDefault(d => d.Name == "UNKNOWN");
            if (domain == null)
            {
                var newDomain = new Domain
                    {
                        Name = "UNKNOWN"
                    };
                db.AddToDomains(newDomain);
                return newDomain;
            }
            return domain;
        }

        public static Unit GetUnitOrDefault(WombatEntities db, string unitName)
        {
                var unkonwnUnit = db.Units
                                    .OrderBy(u => u.Name == "UNKNOWN" ? 1 : 0)
                                    .FirstOrDefault(u => u.Name == "UNKNOWN" || u.Name == unitName);
                if (unkonwnUnit == null)
                {
                    unkonwnUnit = new Unit {Name = "UNKNOWN", Formula = string.Empty};
                    db.Units.AddObject(unkonwnUnit);
                    db.SaveChanges();
                }
                return unkonwnUnit;
        }

    }
}